const App = getApp();

function getAddressDetails(lat, lng) {
  return App.getReverseGeocoder(lat, lng).then((mapdata) => {
    let recommend;
    if (App._isTextEmpty(mapdata.formatted_addresses)) {
      recommend = "";
    } else {
      recommend = mapdata.formatted_addresses.recommend;
    }
    let location = {
      point: { lat, lng },
    };
    if (recommend) {
      location["title"] = recommend;
      location["address"] = mapdata.address;
      location["city"] = !App._isTextEmpty(mapdata.address_component.city) ? mapdata.address_component.city : mapdata.address_component.province;
    }

    // 这里不能 设置"address-point"，不然会与 location组件冲突
    // wx.setStorageSync("address-point", location);   
    return location;
  });
}

export function getLocation() {
  return new Promise((resolve, reject) => {
    const localLocation = wx.getStorageSync("address-point");
    if (localLocation) {
      getAddressDetails(localLocation.point.lat, localLocation.point.lng);
      resolve(localLocation);
      return;
    }
    // wx.///getLocation 删了
  });
}

export function getCustomerService() {
  return new Promise((resolve, reject) => {
    let localData = wx.getStorageSync("projectVerificationCustomerService");
    if (localData && localData.storageTime < Date.now()) {
      localData = null;
    }
    if (!localData) {
      const url = App.getNetAddresss("plugin.store-projects.frontend.index.get-base-info");
      App._getNetWork({
        url,
        success({ data: { data: response, msg, result } }) {
          if (result == 0) {
            wx.showToast({
              title: msg,
              icon: "none",
            });
            return;
          }
          wx.setStorageSync("projectVerificationCustomerService", {
            ...response.cservice,
            storageTime: Date.now() + 1000 * 60 * 60,
          });
          resolve(response.cservice);
        },
        fail(err) {
          reject(err);
        },
      });
    } else {
      resolve(localData);
    }
  });
}

export function getProjectNameLang() {
  const basicInfo = wx.getStorageSync("yz_basic_info");
  if (basicInfo.lang?.store_projects?.project) {
    return basicInfo.lang.store_projects.project;
  } else {
    return "项目";
  }
}
